import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../components/Home.vue'
import Login from '../components/Login.vue'
import Register from '../components/Register'
import Success from '../components/Success.vue'
import Error from '../components/404.vue'
import Statistics from '../components/admin/index.vue'
import User from '../components/user/User.vue'
import CampusAllGood from '../components/campus/AllGood.vue'
import CampusUnTraded from '../components/campus/UnTraded.vue'
import CampusTraded from '../components/campus/Traded.vue'
import Category from '../components/Category.vue'
import UserDonation from '../components/donation/UserDonation.vue'
import ArrivalDonation from '../components/donation/ArrivalDonation.vue'
Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    redirect: '/statistics',
    children: [
      {
        path: '/users',
        component: User
      },
      {
        path: '/campus/allgood',
        component: CampusAllGood
      },
      {
        path: '/campus/untraded',
        component: CampusUnTraded
      },
      {
        path: '/campus/traded',
        component: CampusTraded
      },
      {
        path: '/statistics',
        name: 'Statistics',
        component: Statistics
      },
      {
        path: '/category',
        component: Category
      },
      {
        path: '/donation/userdonation',
        component: UserDonation
      },
      {
        path: '/donation/arrival',
        component: ArrivalDonation
      }
    ]
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/success',
    name: 'Success',
    component: Success
  },
  {
    path: '*',
    name: 'Error',
    component: Error
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/login') { return next() }
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

export default router
